package com.stj.servlet;
import com.stj.entity.Blog;
import com.stj.entity.User;
import com.stj.service.LoginService;
import javafx.application.Application;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        String way = req.getParameter("way");
        if(way.equals("login")){
                this.LoginUser(req,resp);
        } if(way.equals("register")){
            this.registerUser(req,resp);
        }
    }

    private void registerUser(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User(username, password);
        int i = service.register(user);
        if(i>0){
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else{
            req.getRequestDispatcher("register.html").forward(req,resp);
        }
    }

    LoginService service =new LoginService();
    private void LoginUser(HttpServletRequest req, HttpServletResponse resp) throws  IOException, ServletException{
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        User user = new User(userName, passWord);
        HttpSession session = req.getSession();
        User user1 = service.selectOneBlogger(user);
        session.setAttribute("bloggerInfo",user1);
        int i = service.Login(user);
        if(i>0){
            req.getRequestDispatcher("admin/main.jsp").forward(req,resp);
        }else{
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
